﻿@using Seal.Model
@using Seal.Helpers
@{
    Report report = Model;
    ReportView view = report.CurrentView;
    ReportView modelView = report.CurrentModelView;
    ReportModel reportModel = modelView.Model;
    ResultPage page = report.CurrentPage;
    if (page == null) { return; }
    ResultTable table = page.DataTable;

    int trendIndex = view.GetNumericValue("kpi_trend_index");
    string buttonSize = view.GetValue("kpi_button_size");
    string goalSuffix = "_GOAL";
    string newWidgetColor = "", newWidgetIcon = "";
}

@functions {
    public string getValueFromRange(string definition, double value)
    {
        var result = "";
        foreach (var def in definition.Replace("\r\n", "\n").Replace("\r", "\n").Split('\n'))
        {
            if (!string.IsNullOrEmpty(def))
            {
                var defs = def.Split('|');
                if (defs.Length == 1) result = defs[0];
                else if (defs.Length > 1)
                {
                    double threshold;
                    if (double.TryParse(defs[1], out threshold))
                    {
                        if (value < threshold) result = defs[0];
                    }
                }
            }

            if (!string.IsNullOrEmpty(result)) break;
        }
        return result;
    }
}

<div class="@Raw(view.GetValue("kpi_class"))" style="@Raw(view.GetValue("kpi_css"))">
    @{
        for (int col = 0; col < table.ColumnCount && table.RowCount > 1; col++)
        {
            string headerValue = "", lastValue = "", buttonColor = "", buttonIcon = "", goalValue = "", goalColor = "", goalIcon = "";
            double? trendPercentage = null, goalPercentage = null;
            var lastCell = table[table.BodyEndRow - 1, col];
            if (table.BodyStartRow == table.BodyEndRow && table.BodyEndRow < table.RowCount)
            {
                lastCell = table[table.BodyEndRow, col]; //Case only one value
            }
            if (lastCell.Element != null && lastCell.Element.IsNumeric && !lastCell.IsTotal && lastCell.Value != null && lastCell.Element.PivotPosition == PivotPosition.Data && !lastCell.Element.DisplayNameEl.EndsWith(goalSuffix))
            {
                if (table.BodyStartRow == 0) { headerValue = lastCell.Element.DisplayNameElTranslated; }
                else if (table.BodyStartRow == 1 || (table.BodyStartRow == 2 && !reportModel.ShowFirstLine)) { headerValue = table[0, col].HTMLValue; }
                else { headerValue = table[1, col].HTMLValue; }

                lastValue = lastCell.HTMLValue;
                var valueEnd = lastCell.DoubleValue??0;

                double? valueStart = null;
                int rowStart = table.BodyEndRow - 2;
                while (rowStart >= table.BodyStartRow && (trendIndex < 0 || trendIndex + 1 >= table.BodyEndRow - rowStart || valueStart == null))
                {
                    if (table[rowStart, col].Value != null) { valueStart = table[rowStart, col].DoubleValue; }
                    --rowStart;
                }

                double val = 0;
                if (valueStart != null && valueStart != 0 && trendIndex != 0)
                {
                    trendPercentage = 100 * (valueEnd - valueStart) / valueStart;
                    val = trendPercentage.Value;
                }
                buttonColor = getValueFromRange(view.GetValue("kpi_trend_color"), view.GetBoolValue("kpi_trend_color_useval") ? Convert.ToDouble(valueEnd) : val);
                newWidgetColor = buttonColor.Replace("btn-", "");
                buttonIcon = getValueFromRange(view.GetValue("kpi_trend_icon"), view.GetBoolValue("kpi_trend_icon_useval") ? Convert.ToDouble(valueEnd) : val);
                newWidgetIcon = buttonIcon;

                //Check if a Goal is defined
                for (int colGoal = 0; colGoal < table.ColumnCount; colGoal++)
                {
                    var goalCell = table[table.BodyEndRow - 1, colGoal];
                    if (goalCell.Element != null && goalCell.Element.DisplayNameEl == lastCell.Element.DisplayNameEl + goalSuffix && goalCell.Element.IsNumeric && goalCell.Value != null)
                    {
                        goalValue = string.Format("{0}: {1}", report.Translate("Goal"), goalCell.HTMLValue);
                        val = 0;
                        if (goalCell.DoubleValue != null && goalCell.DoubleValue != 0)
                        {
                            goalPercentage = 100 * (valueEnd - goalCell.DoubleValue) / goalCell.DoubleValue;
                            val = goalPercentage.Value;
                        }
                        goalColor = getValueFromRange(view.GetValue("kpi_goal_color"), val);
                        goalIcon = getValueFromRange(view.GetValue("kpi_goal_icon"), val);
                    }
                }

                <span class="text-center btn @buttonColor @buttonSize" title="@Raw(headerValue)" style="@Raw(view.GetValue("kpi_button_css"))">
                    <span class="@buttonIcon" aria-hidden="true"></span>
                    @Raw(view.GetBoolValue("kpi_show_header") ? " " + headerValue + " " : "")
                    <strong>@Raw(view.GetBoolValue("kpi_show_value") ? lastValue : "")</strong>
                    @if (trendPercentage != null)
                    {
                        <span class="badge">@Raw(string.Format(view.GetValue("kpi_trend_pct_format"), trendPercentage.Value))</span>
                    }
                </span>

                if (!string.IsNullOrEmpty(goalValue))
                {
                    <br />
                    <span class="text-center label @goalColor" title="@Raw(headerValue)" style="@Raw(view.GetValue("kpi_goal_css"))">
                        <span class="glyphicon @goalIcon" aria-hidden="true"></span> @Raw(goalValue) @Raw(goalPercentage != null && view.GetValue("kpi_goal_pct_format") != "none" ? string.Format(view.GetValue("kpi_goal_pct_format"), goalPercentage.Value) : "")
                    </span>
                    <br />
                }
            }
        }
    }

    @if (!string.IsNullOrEmpty(newWidgetColor))
    {
        <input type="hidden" id="new-widget-color" name="new-widget-color" value="@newWidgetColor" />
    }
    @if (!string.IsNullOrEmpty(newWidgetIcon))
    {
        <input type="hidden" id="new-widget-icon" name="new-widget-icon" value="@newWidgetIcon" />
    }
</div>